package com.ce.server.service.impl;

import com.ce.server.pojo.Admin;
import com.ce.server.pojo.Menu;
import com.ce.server.mapper.MenuMapper;
import com.ce.server.pojo.Role;
import com.ce.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ce.server.util.AdminUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 郑爽
 * @since 2021-11-14
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

  @Autowired
  MenuMapper menuMapper;
  @Autowired
  RedisTemplate<String, Object> redisTemplate;

  /**
   * 根据当前登录用户id查询拥有菜单
   * @return
   */
  @Override
  public List<Menu> getMenusByAdminId() {
    String no = AdminUtil.getCurrentAdmin().getUsername();
    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
    // 先从redis中获取
    List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + no);
    if (CollectionUtils.isEmpty(menus)){
      // 为空则从数据库中获取
      menus = menuMapper.getMenusById(no);
      valueOperations.set("menu_"+no,menus);
    }
    return menus;
  }

  /**
   * 根据角色获取菜单列表
   * @return
   */
  @Override
  public List<Menu> getMenusWithRole() {
   return menuMapper.getMenusWithRole();

  }

  /**
   * 查询所有菜单
   * @return
   */
  @Override
  public List<Menu> getAllMenus() {
    return menuMapper.getAllMenus();
  }
}
